var app = getApp();
var answerTimer = null;
function checkVal(that,num,rightAnswer){
	if(num!=rightAnswer){
		app.util.request({
	        url: 'entry/wxapp/updateNum',
	        data: {
	          m: 'junsion_challeng',
	          t: 1,
	          openid:that.data.openid,
	          num:num,
	          game:0,
	        },
	        success: function (res) {
	        }
		});
		that.audioCtx.pause()
        that.errAudio.play();
        that.tzFail(num);
        return false;
	}
	else{
		if (num == parseInt(that.data.maxNum)) {//当最大值500输入正确时，运行成功的提示
			that.audioCtx.pause()
			app.checkReward(that,0,num);//中奖了
        }
	}
}
Page({
    data:{
    	openid:'',
    	failtxt:'',
    	suctxt:'',
    	resetTime:0,
    	changeTime:0,
    	mid:0,
    	rid:0,
    	maxNum:0,
        toTem:'Tem',
        change_time:false,
        music:'',
        err_music:'',
        suc_music:'',
        audioCtx:'',
        errAudio:'',
        gametoken:'',
        min_time:0,
        max_time:0,
    },
    onHide:function(){
    	wx.stopBackgroundAudio();
    },
    onLoad:function(options){
    	var that = this;
    	wx.showLoading({title:'数据加载中...'});
    	app.sysInit(this,function(res){
    		app.getUserInfo(function (res) {
    			var openid = res['openid'];
    			app.getShareData(function(res){
	            	that.setData({shareData:res.data});
	            },openid,0);
    			that.setData({openid:openid});
    			app.util.request({
    				url: 'entry/wxapp/play',
    				data: {
    					m: 'junsion_challeng',
    					t: 1,
    					openid:openid,
    				},
    				success: function (res) {
    					wx.hideLoading();
    					if(res.data.code==0 || res.data.code==2){
    						var code = res.data.code;
    						wx.showModal({
    							title:res.data.msg,
    							showCancel:false,
    							success: function(res) {
    								wx.showLoading({title:'数据加载中...'});
    								if(code==2)
    									var url = '../index/index?gobuy=1';
    								else var url = '../index/index';
    								wx.redirectTo({
    									url: url
    								})
    							}
    						});
    					}
    					else{
    						console.log(res);
    						var inputTips=[];
    						var max_num = parseInt(res.data.maxNum);
    						for (var a = 2; a <= max_num; a++) {
    							inputTips.push(a);
    						}
    						that.setData({
    							inputTips: inputTips,
    							gametoken:res.data.gametoken,
    							maxNum:res.data.maxNum,
    							mid:res.data.mid,
    							suctxt:res.data.suctxt,
    							failtxt:res.data.failtxt,
    							resetTime:res.data.resetTime,
    							changeTime:res.data.change_time,
    							min_time:res.data.min_time,
    							max_time:res.data.max_time
    						});
    						if(parseInt(res.data.min_time)<=0){
    							that.setData({change_time : true});
    						}
    						if(parseInt(res.data.min_time)>0 && parseInt(res.data.change_time)>0){
    							that.resetKeyboard();//创建键盘
    							var changeTime = parseInt(res.data.change_time);
    							var timer2=setInterval(function(){
    								changeTime--;
    								if(changeTime>=1){
    									that.setData({
    										changeTime: changeTime
    									})
    								}
    								if (changeTime < 1) {
    									clearInterval(timer2);
    									that.setData({
    										changeTime: 0
    									})
    									that.resetTime();//随机3-10秒刷新键盘顺序
    								}
    							},1000);  
    						}
    						else{
    							that.resetTime();//随机3-10秒刷新键盘顺序
    						}
    					}
    				},
    			});
    		});
    	});
        var music = wx.getStorageSync('music');
        that.setData({
          music:music.music,
  		  err_music:music.err_music,
  	    });
    },	
    onReady:function(e){
        //初始化输入框面板
        var inputTips=[],inputBlank=[];
        for (var a = 2; a <= 200; a++) {
            if (a <= 40) {
                inputTips.push(a);
            } else {
                inputBlank.push('');
            }
        }
        this.setData({
            inputRight:[],//存放已输入的正确答案
            inputTem: [],//存放输入的临时值
            inputActive:[''],//闪烁光标
            inputError:[],
           // inputTips: inputTips,
           // inputBlank: inputBlank
        })
        this.updateInput();//动态更新输入框数据
        this.audioCtx = wx.createAudioContext('myAudio')
        this.errAudio = wx.createAudioContext('errAudio')
        this.audioCtx.play()
    },
    //键盘输入
    play:function(e){
    	var that=this;
        if (!that.data.tiaozhanFail){
            var code = e.currentTarget.dataset.code;
            that.updateInput(code);
            that.setData({toTem:that.data.toTem});
        }
    },
    //动态更新输入框数据
    updateInput:function(code){  
    	var that=this;
        var rightAnswer = this.data.inputRight[this.data.inputRight.length-1]+1||1;
        if (!isNaN(code)){
            if (rightAnswer < 10 && code == rightAnswer){
                this.data.inputTips.shift();
                this.data.inputRight.push(code);
                this.setData({
                    inputRight: this.data.inputRight,
                    inputTips: this.data.inputTips
                })
                checkVal(that,code,rightAnswer);
            } else if (rightAnswer >= 10 && rightAnswer < 100){
                var inputTem = this.data.inputTem[0];
                if (isNaN(inputTem)){
                    this.data.inputTem[0] = code;
                    this.setData({
                        inputTem: this.data.inputTem,
                        inputActive: []
                    })
                } else if (inputTem<10){
                    if (inputTem * 10 + code == rightAnswer){
                        this.data.inputTips.shift();
                        this.data.inputRight.push(inputTem * 10 + code);
                        this.setData({
                            inputTem: [],
                            inputActive: [''],
                            inputRight: this.data.inputRight,
                            inputTips: this.data.inputTips
                        })
                    }else{
                        //this.tzFail(inputTem * 10 + code);
                    }
                    code = inputTem * 10 + code;
                    checkVal(that,code,rightAnswer);
                }     
            } else if (rightAnswer >= 100){
                var inputTem = this.data.inputTem[0];
                if (isNaN(inputTem)) {
                    this.data.inputTem[0] = code;
                    this.setData({
                        inputTem: this.data.inputTem,
                        inputActive: []
                    })
                } else if (inputTem < 10){
                    this.data.inputTem[0] = inputTem * 10+code;
                    this.setData({
                        inputTem: this.data.inputTem
                    })
                } else if (inputTem >= 10 && inputTem<1000) {
                    if (inputTem * 10 + code == rightAnswer) {
                        this.data.inputTips.shift();
                        this.data.inputRight.push(inputTem * 10 + code);
                        this.setData({
                            inputTem: [],
                            inputActive: [''],
                            inputRight: this.data.inputRight,
                            inputTips: this.data.inputTips
                        })
                    } else {
                        //this.tzFail(inputTem * 10 + code);
                    }
                    code = inputTem * 10 + code;
                    checkVal(that,code,rightAnswer);
                }
            } else {
            	checkVal(that,code,rightAnswer);
               // this.tzFail(code);
            }
        }
    },
    //挑战成功
    tzWin:function(e){
    	var that = this;
    	var winMsg = that.data.suctxt;
        for (var a = 0; a < winMsg.length;a++){
        	that.data.inputError.push(winMsg[a]);
        }
        that.setData({
            inputTem: [],
            inputActive: [],
            inputError: that.data.inputError,
            inputTips: [],
            tiaozhanFail: true
        })
    },
    //挑战失败
    tzFail:function(code){
    	var that = this;
    	var failtxt = that.data.failtxt;
    	that.data.inputError.push(code);
    	for (var a = 0; a < failtxt.length;a++){
    		that.data.inputError.push(failtxt[a]);
        }
    	that.setData({
            inputTem:[],
            inputActive: [],
            inputError: that.data.inputError,
            inputTips: [],
            tiaozhanFail: true
        })
        //挑战失败3秒后回到首页
        setTimeout(function(){
        	that.setData({
                inputError: [],
                inputRight: [],
                tiaozhanFail: false
            })
            that.errAudio.pause()
            that.audioCtx.pause()
            wx.showLoading();
        	wx.redirectTo({
	  	    	url: '../tzfail/tzfail'
	  	    })
        },3000)
    },
    onUnload: function(){
  	  clearInterval(answerTimer);
    },
  //调整键盘顺序--倒计时
    resetTime:function(e){
        var that=this;
        if(that.data.change_time) return false;
    	var resetTime = app.fRandomBy(parseInt(that.data.min_time),parseInt(that.data.max_time))
    	that.resetKeyboard();
    	that.setData({resetTime:resetTime});
	      answerTimer=setInterval(function(){
	          resetTime--;
	          if(resetTime>=1){
	        	  that.setData({
	                  resetTime: resetTime
	              })
	          }
	          if (resetTime < 1) {
	              clearInterval(answerTimer);
	              that.resetTime();
	          }
	      },1000);
	     
    },
    //调整键盘顺序
    resetKeyboard:function(e){
        var keyboard = this.data.keyboard || [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
        var temArray=[];
        for (var i = 0, len = keyboard.length; i < len; i++) {
            var j = Math.floor(Math.random() * keyboard.length);
            temArray[i] = keyboard[j];
            keyboard.splice(j, 1);
        }
        this.setData({
            keyboard: temArray
        })
    }
})